<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <nav class="nav-container">
        <div class="nav-left">
          <a href="#" class="nav-item active">主页大厅</a>
          <a href="#" class="nav-item" @click="handleTeacherTeams">教师队伍</a>
        </div>
        <div class="nav-right">
          <button class="user-btn" @click="handleProfileClick">
            <span class="user-icon">👤</span>我的
          </button>
        </div>
      </nav>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 轮播图展示区 -->
      <section class="carousel-section">
        <div class="carousel-container">
          <div class="carousel-wrapper">
            <div v-for="(image, index) in activeCarouselImages" :key="image.position" class="carousel-slide"
              :class="{ active: index === currentSlide }">
              <img :src="image.imageUrl" :alt="image.imageName" />

            </div>
          </div>

          <!-- 轮播指示器 -->
          <div class="carousel-indicators">
            <button v-for="(image, index) in activeCarouselImages" :key="index" class="indicator"
              :class="{ active: index === currentSlide }" @click="goToSlide(index)"></button>
          </div>

          <!-- 轮播控制按钮 -->
          <button class="carousel-btn prev" @click="prevSlide">‹</button>
          <button class="carousel-btn next" @click="nextSlide">›</button>
        </div>
      </section>

      <!-- 功能卡片区 -->
      <section class="feature-section">
        <div class="feature-cards">
          <div class="feature-card" @click="handleRecentEvents">
            <div class="card-image">
              <!-- <img  alt="近期赛事" /> -->
            </div>
            <div class="card-content">
              <h3>近期赛事</h3>
            </div>
          </div>

          <div class="feature-card" @click="handleLatestNews">
            <div class="card-image">
              <!-- <img alt="最新通知" /> -->
            </div>
            <div class="card-content">
              <h3>最新通知</h3>
            </div>
          </div>
        </div>
      </section>

      <!-- 最新新闻区 -->
      <section class="intro-section">
        <div class="intro-content">
          <h2 style="border-bottom: 2px solid #e9ecef;padding-bottom: 10px;">最新新闻</h2>

          <!-- 新闻列表 -->
          <div class="news-list" v-if="newsList.length > 0">
            <div v-for="news in newsList" :key="news.id" class="news-item" @click="handleNewsClick(news.id)">
              <h3 class="news-title">{{ news.title }}</h3>
              <div class="news-summary" v-if="news.summary">
                <p>{{ news.summary }}</p>
              </div>
            </div>
          </div>

          <!-- 暂无新闻 -->
          <div class="no-news" v-else>
            <p>暂无新闻数据</p>
          </div>
        </div>
        <button class="footer-btn" @click="handleMoreInfo">了解更多相关信息</button>
      </section>


    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTeacherStore } from '@/stores/teacher.js'
import { useTokenStore } from '@/stores/token.js'
import { getCarouselImagesService, getAllNewsService } from '@/api/home.js'

const router = useRouter()
const teacherStore = useTeacherStore()
const tokenStore = useTokenStore()

// 轮播图数据
const carouselImages = ref([])
const currentSlide = ref(0)
let carouselTimer = null

// 新闻数据
const newsList = ref([])

// 计算属性：获取教师姓名
const teacherName = computed(() => {
  return teacherStore.getTeacherName() || '教师'
})

// 计算属性：获取启用的轮播图
const activeCarouselImages = computed(() => {
  return carouselImages.value.filter(img => img.isActive && img.imageUrl)
})

// 轮播图控制
const goToSlide = (index) => {
  currentSlide.value = index
}

const nextSlide = () => {
  if (activeCarouselImages.value.length > 0) {
    currentSlide.value = (currentSlide.value + 1) % activeCarouselImages.value.length
  }
}

const prevSlide = () => {
  if (activeCarouselImages.value.length > 0) {
    currentSlide.value = currentSlide.value === 0
      ? activeCarouselImages.value.length - 1
      : currentSlide.value - 1
  }
}

// 自动轮播
const startCarousel = () => {
  if (activeCarouselImages.value.length > 1) {
    carouselTimer = setInterval(() => {
      nextSlide()
    }, 5000) // 5秒切换一次
  }
}

const stopCarousel = () => {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 加载轮播图数据
const loadCarouselImages = async () => {
  try {
    const result = await getCarouselImagesService()
    if (result.code === 200 && result.data) {
      carouselImages.value = result.data.sort((a, b) => a.position - b.position)
      // 启动自动轮播
      startCarousel()
    }
  } catch (error) {
    console.error('加载轮播图失败:', error)
  }
}

// 加载新闻数据
const loadNewsList = async () => {
  try {
    const result = await getAllNewsService()
    if (result.code === 200 && result.data && result.data.list) {
      // 只取前3条新闻
      newsList.value = result.data.list.slice(0, 3)
    }
  } catch (error) {
    console.error('加载新闻数据失败:', error)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 点击新闻项跳转到详情
const handleNewsClick = (newsId) => {
  router.push(`/news-detail/${newsId}`)
}

// 检查登录状态并加载数据
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadCarouselImages()
  loadNewsList()
})

// 页面销毁时清理定时器
onUnmounted(() => {
  stopCarousel()
})

// 个人信息点击
const handleProfileClick = () => {
  router.push('/profile')
}

// 教师队伍点击
const handleTeacherTeams = () => {
  router.push('/teacher-list')
}

// 近期赛事点击
const handleRecentEvents = () => {
  router.push('/events-list')
}

// 最新通知点击
const handleLatestNews = () => {
  router.push('/notifications-list')
}

// 了解更多信息
const handleMoreInfo = () => {
  router.push('/news-list')
}
</script>

<style scoped lang="scss">
@import '@/assets/css/home.css';
</style>